package com.easyUploader.listener;

import com.easyUploader.property.LocalFileProperty;
import com.easyUploader.util.FileUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.File;


/**
 * 应用启动监听器
 * @author 大忽悠
 * @create 2022/11/23 12:35
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class AppStartListener implements ApplicationRunner {
    private final LocalFileProperty localFileProperty;

    @Override
    public void run(ApplicationArguments args) throws Exception {
           baseDirCheck(localFileProperty);
           spaceCheck(localFileProperty);
           defaultHeadImgCheck(localFileProperty);
    }

    private void defaultHeadImgCheck(LocalFileProperty localFileProperty) {
        File defaultHeadImgDir = new File(localFileProperty.getDefaultHeadImgDirPath());
        if(!defaultHeadImgDir.exists()|| ObjectUtils.isEmpty(defaultHeadImgDir.listFiles())){
            log.error("默认头像目录={}不存在或者并没有提供默认头像,这会导致新注册用户没有默认头像可用!!!",localFileProperty.getDefaultHeadImgDirPath());
        }
    }

    /**
     * 如果用户空间,系统空间和共享空间相关目录没有创建,则进程创建
     */
    private void spaceCheck(LocalFileProperty localFileProperty) {
        FileUtil.createDirIfNotExist(localFileProperty.getUserSpacePath(),false);
        log.info("用户空间={}初始化中....",localFileProperty.getUserSpacePath());
        FileUtil.createDirIfNotExist(localFileProperty.getSystemSpacePath(),false);
        log.info("系统空间={}初始化中....",localFileProperty.getSystemSpacePath());
        FileUtil.createDirIfNotExist(localFileProperty.getShareSpacePath(),false);
        log.info("共享空间={}初始化中....",localFileProperty.getShareSpacePath());
    }

    /**
     * 如果baseDir目录没有创建,则进行创建
     */
    private void baseDirCheck(LocalFileProperty localFileProperty) {
        FileUtil.createDirIfNotExist(localFileProperty.getBaseDir(),false);
        log.info("baseDir={}初始化中....",localFileProperty.getBaseDir());
    }
}
